package com.limi.java8.streams;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @Description: TODO
 * @Author Limi Pan
 * @Date 2018-10-23 22:51
 * @Version v1.0
 */
public class ForkJoinTest {

    @Test
    public void test1(){
        //Java8计算时间方式
        Instant start = Instant.now();

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinCalculate(0, 100000000000L);
        Long sum = pool.invoke(task);
        System.out.println(sum);

        Instant end = Instant.now();
        System.out.println("耗时："+Duration.between(start, end).toMillis());

    }

    @Test
    public void test2(){
        //Java8计算时间方式
        Instant start = Instant.now();

        long sum = 0L;
        for (long i = 0; i < 100000000000L; i++) {
            sum += i;
        }
        System.out.println(sum);

        Instant end = Instant.now();
        System.out.println("耗时："+Duration.between(start, end).toMillis());//30125

    }

    @Test
    public void test3(){
        //Java8计算时间方式
        Instant start = Instant.now();

        long sum = LongStream.rangeClosed(0, 10000000000L)
                .parallel()//切换为并行流
                .reduce(0, Long::sum);
        System.out.println(sum);

        Instant end = Instant.now();
        System.out.println("耗时："+Duration.between(start, end).toMillis());//22056

    }
}

